# To change this template, choose Tools | Templates
# and open the template in the editor.
$LOAD_PATH.unshift File.join(File.dirname(__FILE__),'../..','ext_pr1/lib')
require 'ext_pr1_v4'


#Summe aller Natürlichen Zahlen von 1 bis n
#summe ::= (n) :: Nat -> Nat
#test sum(0) -> 0, sum(1) -> 1, sum(2) -> 3
#sum(-1) -> err, sum("a") -> err

def sum(n)
  check_pre((
      n.nat?
      ))
#  n == 0 ? 0 : n + sum(n-1)
sum_(0,n)
end

def sum_(accu,n)
#n <= 0 ? accu : sum_(accu+n,n-1)

  while (n >= 0)
    accu = accu + n
    n = n - 1
  end
accu
end


#Berechnung der Potenz
#potenz ::= (x,n) :: Nat x Nat -> Nat
#test potenz(1,0) -> 1, potenz(1,1) -> 1, potenz(2,2) ->4, potenz(5,5) -> 3125
#potenz(-1,1) -> err, potenz("a",1) -> err

def potenz(x,n)
  check_pre((
    n.nat? and 
    x.nat?))
    
  potenz_(1,x,n)
  #n == 0 ? 1 : x * potenz(x, n-1)
end

def potenz_(accu,x,n)
  
  #n == 0  ? accu : x * potenz_(accu,x,n-1)
  
  while (n > 0)
    accu = accu * x
    n = n - 1
  end
 accu 
end

#Berechnung von Fibonacci
#fibonacci ::= (n) :: Nat -> Nat
#test fibo(0) -> 0, fibo(1) -> 1, fibo(2) -> 1
#fibo(3) -> 2, fibo(4) -> 3, fibo(5) -> 5
#fibo(-1) -> err, fibo("a") -> err

def fibo(n)
  check_pre((
    n.nat?))
  
  n == 0 ? 0 : n == 1 ? 1 : fibo(n-1) + fibo(n-2)
  
  #fibo_(0,1,n)
end

#def fibo_(accu_a, accu_b,n)

#end


